<?php

namespace App\Http\Controllers;

use App\Models\FinancingListModel;
use App\Models\Member\MemberAuthModel;
use App\Models\Member\MemberPaymentModel;
use App\Models\Member\MemberRoleModel;
use App\Models\MembersModel;
use App\Models\MembersModel as Members;
use App\Models\MemberWalletModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;


class MembersController extends Controller
{

    public function memberRoleList(Request $request)
    {
        $firstWhere = function ($query) use ($request) {
            if ($request->has('status') and $request->status != '') {
                $query->where('member_role.status', $request->status);
            }
            if ($request->has('shen') and (int)$request->shen > 0) {
                $query->where('member_role.shen', (int)$request->shen);
            }
            if ($request->has('interview') and (int)$request->interview > 0) {
                $query->where('member_role.interview', (int)$request->interview);
            }
        };

        $where = function ($query) use ($request) {
            //筛选查询关键字
            if ($request->has('keywords') and $request->keywords != '') {
                $query->orWhere('member.name', '=', $request->keywords)
                    ->orWhere('member_role.member_id', '=', $request->keywords)
                    ->orWhere('member.phone', '=', $request->keywords)
                    ->orWhere('member_role.id', '=', $request->keywords);
            }
        };

        $data = MemberRoleModel::where($firstWhere)
            ->where($where)
            ->join('member', 'member_role.member_id', '=', 'member.id')
            ->select('member_role.*', 'member.phone as member_phone', 'member.name as member_name', 'member.role_shen', 'member.role_interview')
            ->paginate($request->get('count'));
        return self::returnMsg($data);
    }

    public function memberRoleEdit(Request $request)
    {
        $rules  = [
            'id'      => 'required|integer|min:1',
            'status'  => 'required|integer|in:0,1,2',
            'message' => 'max:255'
        ];
        $sqlmap = self::checkValidate($rules, $request->all());

        $member_roel = MemberRoleModel::with('member')->find($sqlmap['id']);
        if (!isset($member_roel))
            return self::errorMsg('没有找到该申请');
        $member_roel->status  = $sqlmap['status'];
        $member_roel->message = isset($sqlmap['message']) ? $sqlmap['message'] : $member_roel->message;
        try {
            $member_roel->save();
            if ($sqlmap['status'] == 1) {
                //通过申请
                $member_roel->member->role_shen      = $member_roel->shen > 0 ? $member_roel->shen : $member_roel->member->role_shen;
                $member_roel->member->role_interview = $member_roel->interview > 0 ? $member_roel->interview : $member_roel->member->role_interview;
                $member_roel->member->save();
            }
            return self::successMsg();
        } catch (\Exception $exception) {
            return self::errorMsg($exception->getMessage());
        }
    }

    public function memberEdit(Request $request)
    {
        $rules  = [
            'name'           => 'min:2|max:12',
            'exp_interview'  => 'required|integer|min:0',
            'exp_shen'       => 'required|integer|min:0',
            'exp_mvp'        => 'required|integer|min:0',
            'rank'           => 'required|integer|min:0',
            'describe'       => 'max:255',
            'role_shen'      => 'required|integer|in:0,1,2,3',
            'role_interview' => 'required|integer|in:0,1,2,3',
            'auth'           => 'required|integer|in:0,1',
            'id'             => 'required|integer|min:0',
        ];
        $sqlmap = self::checkValidate($rules, $request->all());
        $member = MembersModel::find($sqlmap['id']);
        if (!isset($member))
            return self::errorMsg('没有找到该会员信息');
        $member->name           = isset($sqlmap['name']) ? $sqlmap['name'] : $member->name;
        $member->exp_interview  = isset($sqlmap['exp_interview']) ? $sqlmap['exp_interview'] : $member->exp_interview;
        $member->exp_shen       = isset($sqlmap['exp_shen']) ? $sqlmap['exp_shen'] : $member->exp_shen;
        $member->exp_mvp        = isset($sqlmap['exp_mvp']) ? $sqlmap['exp_mvp'] : $member->exp_mvp;
        $member->describe       = isset($sqlmap['describe']) ? $sqlmap['describe'] : $member->describe;
        $member->role_shen      = isset($sqlmap['role_shen']) ? $sqlmap['role_shen'] : $member->role_shen;
        $member->role_interview = isset($sqlmap['role_interview']) ? $sqlmap['role_interview'] : $member->role_interview;
        $member->auth           = isset($sqlmap['auth']) ? $sqlmap['auth'] : $member->auth;

        try {
            $member->save();
            return self::successMsg();
        } catch (\Exception $exception) {
            return self::errorMsg($exception->getMessage());
        }
    }

    public function paymentEdit(Request $request)
    {
        $id     = (int)$request->input('id');
        $stauts = (int)$request->input('status');
        $auth   = MemberPaymentModel::find($id);
        if (!isset($auth))
            return self::errorMsg('没有找到该收款信息');
        $auth->status = $stauts;
        try {
            $auth->save();
            return self::successMsg();
        } catch (\Exception $exception) {
            return self::errorMsg($exception->getMessage());
        }
    }

    public function paymentList(Request $request)
    {
        $where = function ($query) use ($request) {
            //筛选查询关键字
            if ($request->has('keywords') and $request->keywords != '') {
                $query->orWhere('member.name', '=', $request->keywords)
                    ->orWhere('member_payment.member_id', '=', $request->keywords)
                    ->orWhere('member.phone', '=', $request->keywords)
                    ->orWhere('member_payment.acount', '=', $request->keywords)
                    ->orWhere('member_payment.name', '=', $request->keywords)
                    ->orWhere('member_payment.id', '=', $request->keywords);

            }
            if ($request->has('status') and $request->status != '') {
                $query->where('member_payment.status', $request->status);
            }
        };
        $data  = MemberPaymentModel::where($where)
            ->join('member', 'member_payment.member_id', '=', 'member.id')
            ->select('member_payment.*', 'member.phone as member_phone', 'member.name as member_name')
            ->paginate($request->get('count'));
        return self::returnMsg($data);
    }

    public function authEdit(Request $request)
    {
        $id     = (int)$request->input('id');
        $stauts = (int)$request->input('status');
        $remark = $request->input('remark');
        $auth   = MemberAuthModel::find($id);
        if (!isset($auth))
            return self::errorMsg('没有找到该实名认证信息');
        $auth->status = $stauts;
        $auth->remark = $remark;
        try {
            $auth->save();
            if ($stauts == 1) {
                $member       = MembersModel::find($auth->member_id);
                $member->auth = 1;
                $member->save();
            } else {
                $member       = MembersModel::find($auth->member_id);
                $member->auth = 0;
                $member->save();
            }
            return self::successMsg();
        } catch (\Exception $exception) {
            return self::errorMsg($exception->getMessage());
        }
    }

    public function authList(Request $request)
    {
        $where = function ($query) use ($request) {
            //筛选查询关键字
            if ($request->has('keywords') and $request->keywords != '') {
                $query->orWhere('member.name', '=', $request->keywords)
                    ->orWhere('member_auth.member_id', '=', $request->keywords)
                    ->orWhere('member.phone', '=', $request->keywords)
                    ->orWhere('member_auth.id_card', '=', $request->keywords)
                    ->orWhere('member_auth.name', '=', $request->keywords)
                    ->orWhere('member_auth.id', '=', $request->keywords);
            }
            if ($request->has('status') and $request->status != '') {
                $query->where('member_auth.status', $request->status);
            }
        };
        $data  = MemberAuthModel::where($where)
            ->join('member', 'member_auth.member_id', '=', 'member.id')
            ->select('member_auth.*', 'member.phone as member_phone', 'member.name as member_name')
            ->paginate($request->get('count'));
        return self::returnMsg($data);
    }

    public function financingMold()
    {
        $data = DB::table('financing_mold')->get();
        return self::returnMsg($data);
    }

    public function financingProfit(Request $request)
    {
        $where = function ($query) use ($request) {
            //筛选查询关键字
            if ($request->has('keywords') and $request->keywords != '') {
                $keywords = "%" . $request->keywords . "%";
                $query->orWhere('member.name', 'like', $keywords)->orWhere('financing_profit.member_id', 'like', $keywords)
                    ->orWhere('member.phone', 'like', $keywords);
            }
            if ($request->has('mold_id') and (int)$request->mold_id > 0) {
                $query->where('financing_profit.mold_id', $request->mold_id);
            }
            if ($request->has('date') and $request->date != '') {
                $start = strtotime($request->date[0]);
                $end   = strtotime($request->date[1]);
                $query->whereBetween('financing_profit.create_time', [$start, $end]);
            }
        };
        $data  = DB::table('financing_profit')
            ->where($where)
            ->join('member', 'financing_profit.member_id', '=', 'member.id')
            ->select('financing_profit.*', 'member.phone', 'member.name')
            ->paginate($request->get('count'));
        return self::returnMsg($data);
    }

    public function financingList(Request $request)
    {
        $where = function ($query) use ($request) {
            //筛选查询关键字
            if ($request->has('keywords') and $request->keywords != '') {
                $keywords = "%" . $request->keywords . "%";
                $query->orWhere('member.name', 'like', $keywords)->orWhere('financing_list.member_id', 'like', $keywords)
                    ->orWhere('member.phone', 'like', $keywords);
            }
            if ($request->has('mold_id') and (int)$request->mold_id > 0) {
                $query->where('financing_list.mold_id', $request->mold_id);
            }
            if ($request->has('date') and $request->date != '') {
                $start = strtotime($request->date[0]);
                $end   = strtotime($request->date[1]);
                $query->whereBetween('financing_list.create_time', [$start, $end]);
            }
        };
        $data  = DB::table('financing_list')
            ->where($where)
            ->join('member', 'financing_list.member_id', '=', 'member.id')
            ->select('financing_list.*', 'member.phone', 'member.name')
            ->paginate($request->get('count'));
        return self::returnMsg($data);
    }

    /**
     * @func获取用户会员列表
     */
    public function membersList(Request $request)
    {
        $where      = function ($query) use ($request) {
            //筛选查询关键字
            if ($request->has('keywords') and $request->keywords != '') {
                $keywords = "%" . $request->keywords . "%";
                $query->orWhere('member.name', 'like', $keywords)->orWhere('member.id', 'like', $keywords)
                    ->orWhere('member.phone', 'like', $keywords);
            }
        };
        $bannerlist = Members::GetPageList($request->get('count'), $where);
        return self::returnMsg($bannerlist, '', 20000);
    }

    public function memberWalletList(Request $request)
    {
        $member_id = (int)$request->input('id');
        $data      = MemberWalletModel::find($member_id);
        return self::returnMsg($data);
    }

    /**
     * @func查看我的下级
     */
    public function subList(Request $request)
    {
        $where      = function ($query) use ($request) {
            //筛选查询关键字
            if ($request->has('ParentId') and $request->ParentId != '') {
                $query->where('member.pid', '=', $request->ParentId);
            }
        };
        $bannerlist = Members::GetPageList($request->get('count'), $where);
        return self::returnMsg($bannerlist);
    }


    /**
     * 禁用会员账户
     */
    public function membersStatus(Request $request)
    {
        $type       = (int)$request->input('type');
        $id         = (int)($request->input('id'));
        $member_arr = Members::GetBId($id);
        if (!$member_arr) {
            return self::returnMsg([], '对不起，没有找到用户', 20001);
        }
        if ($type > 0) {
            //冻结用户，不能提现
            if ($member_arr['IsFreeze'] > 0) {
                $result = Members::where(['id' => $id])->update(['IsFreeze' => 0]);
            } else {
                $result = Members::where(['id' => $id])->update(['IsFreeze' => 1]);
            }
        } else {
            //锁定用户
            if ($member_arr['status'] > 0) {
                $result = Members::where(['id' => $id])->update(['status' => 0]);
            } else {
                $result = Members::where(['id' => $id])->update(['status' => 1]);
            }
        }

        if ($result) {
            return self::returnMsg([], '操作成功', 20000);
        } else {
            return self::returnMsg([], '操作失败', 20011);
        }
    }

    public function profitEdit(Request $request)
    {
        try {
            $rules  = [
                'member_id' => 'required|integer|min:1',
                'money'     => 'required|numeric',
            ];
            $sqlmap = self::checkValidate($rules, $request->all());
            DB::beginTransaction();
            $wallet = MemberWalletModel::where('member_id', $sqlmap['member_id'])->first();
            if (!isset($wallet))
                return self::errorMsg('没有找到该用户的钱包');

            $wallet->profit += $sqlmap['money'];

            if ($wallet->profit < 0)
                return self::errorMsg('用户收益不足');

            FinancingListModel::write_profit($sqlmap['member_id'], $sqlmap['money'], $wallet->profit, 'admin_edit_profit', '后台修改用户收益');
            $wallet->save();
            DB::commit();
            return self::successMsg();
        } catch (\Exception $exception) {
            DB::rollBack();
            return self::errorMsg($exception->getMessage());
        }
    }

    public function moneyEdit(Request $request)
    {
        try {
            $rules  = [
                'member_id' => 'required|integer|min:1',
                'money'     => 'required|numeric',
            ];
            $sqlmap = self::checkValidate($rules, $request->all());
            DB::beginTransaction();
            $wallet = MemberWalletModel::where('member_id', $sqlmap['member_id'])->first();
            if (!isset($wallet))
                return self::errorMsg('没有找到该用户的钱包');

            $wallet->money += $sqlmap['money'];

            if ($wallet->money < 0)
                return self::errorMsg('用户余额不足');

            FinancingListModel::write_log($sqlmap['member_id'], $sqlmap['money'], $wallet->money, 'admin_edit_money', '后台修改用户余额');
            $wallet->save();
            DB::commit();
            return self::successMsg();
        } catch (\Exception $exception) {
            dd($exception);
            DB::rollBack();
            return self::errorMsg($exception->getMessage());
        }
    }


}
